/*
 * Created on 12. des.. 2006
 * Created by Tomas
 */
package gui;

import java.io.Serializable;

import javax.swing.event.TreeModelEvent;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import placing.Mapper;
import placing.Place;
import placing.Room;

public class RoomTreeModel extends AbstractTreeModel implements Serializable {
	private static final long serialVersionUID = 1L;
	private DefaultMutableTreeNode root;
	private Presenter parent;
	private Mapper map;

	public RoomTreeModel(Presenter p) {
		parent = p;
		root = new DefaultMutableTreeNode();
		map = p.getCurrentMapper();
	}

	public Object getChild(Object parent, int index) {
		//if the parent is the root - return a room
		if (parent == root) {
			return map.getRooms().get(index);
		}
		//if the parent is a room - return a place
		return ((Room)parent).getPlaces().get(index);
		
	}

	public int getChildCount(Object parent) {
		//If the parent is the root - return the number of rooms
		if (parent == root) {
			return map.getRooms().size();
		}
		
		//If the parent is a room - return the number of places in the room
		try {
			return ((Room)parent).getPlaces().size();
		} catch (ClassCastException e) { //it's a place - 0 children
			return 0;
		}
	}

	public int getIndexOfChild(Object parent, Object child) {
		if (parent == root) {
			return map.getRooms().indexOf(child);
		}
		return ((Room)parent).getPlaces().indexOf((Place)child);
	}

	public Object getRoot() {
		return root;
	}

	/*
	 * If the object is a place it will be a leaf
	 */
	public boolean isLeaf(Object node) {
		return (getChildCount(node) == 0);
	}


	/*
	 * Messaged when the user changes the value at a path
	 */
	public void valueForPathChanged(TreePath path, Object newValue) {
		map = parent.getCurrentMapper();
		TreePath p = path;
		if (p == null) {
			p = new TreePath(getRoot());
		}
		fireTreeStructureChanged(new TreeModelEvent(this, p));
	}


}
